#!/bin/bash

#########################################################################
#                                                                       #
# Nombre: torrent_add_beta.sh                                           #
# Version: 0.1b                                                         #
# Author: A.Ruiz                                                        #
# Desc: Identifica y añade a Transmission                               #
#		los .torrent de la ruta de entrada                              #
#                                                                       #
#########################################################################

LOG_FILE='/aplicaciones/logs-server/torrent_add.log'
LOG_EJE=`date +%d/%m/%Y %H:%M`

# GENERAMOS FICHERO LOG SI ES NECESARIO
if [ ! -f $LOG_FILE ]; then
	touch $LOG_FILE
fi

#VARIABLES PATH
PATH_IMPUT=/nas/torrents/imput/
PATH_REJECT=/nas/torrents/reject/
PATH_ADDED=/nas/torrents/added/
PATH_DLD=/nas/caja_negra_nas/incoming/

TR_PARAMS="--auth=transmission:transmission"

echo "INIT - torrent_add_beta.sh - () " >> $LOG_FILE

#COMPROBAMOS QUE TRANSMISSION ESTA ARRIBA
transmission-remote $TR_PARAMS -st  > /dev/null
if [ ! $? -eq 0 ]; then
	echo "TRANSMISSION IS DOWN" >> $LOG_FILE
	echo "END WITH ERROR - torrent_add_beta.sh - " >> $LOG_FILE
	exit 1
fi

for TORRENT_FILE in "`ls $PATH_IMPUT*.torrent`"; do
	#PRIMERO OBTENEMOS HASH DEL TORRENT
	TORRENT_HASH=`lstor "$PATH_IMPUT$TORRENT_FILE" -qo __hash__`
	
	#CREAMOS UNA ENTRADA EN EL REGISTRO DE BBDD
	if [ $? -eq 0 ]; then
		#INSERTAMOS INFO EN BBDD
		sql-plus ... 
	else
		
	
	fi
	
	#AÑADIMOS A TRANSMISSION
	transmission-remote $TR_PARAMS -a $TORRENT_FILE
	if [ $? -eq 0 ]; then
		cp $PATH_IMPUT$TORRENT_FILE $PATH_ADDED
		rm $PATH_IMPUT$TORRENT_FILE
		echo "TORRENT ADDED: $TORRENT_FILE - $TORRENT_HASH" >> $LOG_FILE	
		echo "INFO: to categorize torrent run /aplicaciones/scripts_src/torrent_taging_beta.sh $TORRENT_HASH \[TAG\]" >> $LOG_FILE
	else 
		cp $PATH_IMPUT$TORRENT_FILE $PATH_REJECT
		rm $PATH_IMPUT$TORRENT_FILE
		echo "TORRENT REJECTED: $TORRENT_FILE - $TORRENT_HASH" >> $LOG_FILE
	fi
done


echo "END WITHOUT ERROR - torrent_add_beta.sh - " >> $LOG_FILE
exit 0